use sea_orm::{
    ColumnTrait, DatabaseConnection, DbErr, EntityTrait, PaginatorTrait, QueryFilter, QueryOrder,
};
use sky_common::constant::message;

use sky_pojo::dto::employee::EmployeePageQueryDTO;
use sky_pojo::entities::employee;
use sky_pojo::vo::employee::EmployeeVO;
use sky_pojo::vo::PageResult;

pub async fn get_by_username(
    db: DatabaseConnection,
    username: String,
) -> Result<employee::Model, String> {
    let employee = employee::Entity::find()
        .filter(employee::Column::Username.contains(username))
        .one(&db)
        .await;

    match employee {
        Ok(None) => Err(message::ACCOUNT_NOT_FOUND.to_string()),
        Ok(Some(emp)) => Ok(emp),
        Err(err) => {
            tracing::error!("{}", err);
            Err(message::UNKNOWN_ERROR.to_string())
        }
    }
}

pub async fn insert(
    db: DatabaseConnection,
    employee: employee::ActiveModel,
) -> Result<employee::Model, DbErr> {
    let result = employee::Entity::insert(employee)
        .exec_with_returning(&db)
        .await?;

    Ok(result)
}

pub async fn page_query(
    db: DatabaseConnection,
    query: EmployeePageQueryDTO,
) -> Result<PageResult<EmployeeVO>, DbErr> {
    let mut stmt = employee::Entity::find();

    if let Some(id) = query.id {
        stmt = stmt.filter(employee::Column::Id.eq(id));
    }

    // 条件过滤
    if let Some(name) = query.name {
        if !name.is_empty() {
            stmt = stmt.filter(employee::Column::Name.contains(&name));
        }
    }

    // 总记录数
    let total: u64 = stmt.clone().count(&db).await?;

    // 分页数据
    let data: Vec<employee::Model> = stmt
        .order_by_desc(employee::Column::CreateTime)
        .paginate(&db, query.page_size.try_into().unwrap())
        .fetch_page((query.page - 1).try_into().unwrap())
        .await?;

    let employee_vo_vec: Vec<EmployeeVO> =
        data.into_iter().map(|emp| EmployeeVO::from(emp)).collect();

    Ok(PageResult {
        total,
        records: employee_vo_vec,
    })
}

pub async fn find_by_id(db: DatabaseConnection, id: i64) -> Result<EmployeeVO, String> {
    let result = employee::Entity::find_by_id(id).one(&db).await;

    match result {
        Ok(None) => Err(format!("id {} 不存在", id)),
        Ok(Some(emp)) => Ok(EmployeeVO::from(emp)),
        Err(err) => Err(err.to_string()),
    }
}

pub async fn update_employee(
    db: DatabaseConnection,
    update_model: employee::ActiveModel,
    id: i64,
) -> Result<EmployeeVO, String> {
    let result = employee::Entity::update(update_model)
        .exec(&db)
        .await;

    match result {
        Ok(model) => Ok(EmployeeVO::from(model)),
        Err(e) => Err(format!("Database error: {}", e)),
    }
}

pub async fn modify_password(
    db: DatabaseConnection,
    update_model: employee::ActiveModel,
    id: i64,
    old_pass: String,
) -> Result<EmployeeVO, String> {
    let result: Result<Vec<employee::Model>, DbErr> = employee::Entity::update_many()
        .filter(employee::Column::Id.eq(id))
        .filter(employee::Column::Password.eq(old_pass))
        .set(update_model)
        .exec_with_returning(&db)
        .await;

    match result {
        Ok(updated_rows) => {
            if !updated_rows.is_empty() {
                Ok(EmployeeVO::from(updated_rows[0].clone()))
            } else {
                Err("No rows updated".to_string())
            }
        }
        Err(e) => Err(format!("Database error: {}", e)),
    }
}
